// FIXME(CFY) 使用 script js 引入
// import axios from 'axios';
import Vue from 'vue';
import { ToastPlugin, LoadingPlugin, AlertPlugin } from 'vux';
import logan from '@/common/logan';
import i18n from '@/common/i18n';

// 使用cookies 存储 token
import { getToken } from '@/utils/auth';

// 使用jssdk存储至豆豆客户端
// import { getToken } from '@/utils/auth-jssdk';

import { getLanguage } from '@/common/i18n';

Vue.use(ToastPlugin);
Vue.use(LoadingPlugin);
Vue.use(AlertPlugin);

// 获取访问 url 中的端口号
const host = window.location.host;

// 判断是http协议还是https协议
const ishttps = document.location.protocol;

// 接口域名
export const domain = `${ishttps}//${host}`;

const service = axios.create({
  baseURL: `${domain}/app-template`,
  withCredentials: true, // send cookies when cross-domain requests
  credentials: 'include',
  timeout: 5000, // request timeout
});

function getCommonStatus(status) {
  if (status === 404 || status === 400) {
    return `${status}`;
  }

  if (status >= 400 && status < 500) {
    return '40X';
  }

  if (status >= 500) {
    return '50X';
  }

  return 'unknown';
}

function errorHandler(error) {
  if (error.response.status === 401) {
    logan.error(error.response.config.url);
    if (error.response.config.url.includes('/api/login')) {
      handleErrorMsg(error);
      return;
    }

    Vue.$vux.alert.show({
      title: i18n.t('common.tips'),
      content: i18n.t('common.noSession'),
    });
    // TODO 需要关闭应用
    return;
  }

  handleErrorMsg(error);
}

function handleErrorBlob(blob, status) {
  const reader = new FileReader();
  reader.onload = (event) => {
    const result = reader.result;
    const data = JSON.parse(result);
    const message = (data.desc || data.message) ? (data.desc || data.message) : i18n.t(`error.${status}`);

    Vue.$vux.toast.show({
      text: message,
      type: 'warn',
      time: 4000,
      width: '10em',
      position: 'top',
    });
  };
  reader.readAsText(blob);
}

function handleErrorMsg(error) {
  let message = '';
  const status = getCommonStatus(error.response.status);
  if (error.response && error.response.data) {
    const data = error.response.data;
    if (data instanceof Blob) {
      handleErrorBlob(data, status);
      return;
    }

    message = (data.desc || data.message) ? (data.desc || data.message) : i18n.t(`error.${status}`);
  } else {
    message = i18n.t(`error.${status}`);
  }

  Vue.$vux.toast.show({
    text: message,
    type: 'warn',
    time: 4000,
    width: '10em',
    position: 'top',
  });
}

const languages = {
  zh: 'zh-cn',
  en: 'en-us',
};
// request interceptor
service.interceptors.request.use(
  async(config) => {
    const token = await getToken();
    if (token) {
      config.headers['Authorization'] = token;
    }
    config.headers['accept-language'] = languages[getLanguage()];
    return config;
  },
  error => {
    // do something with request error
    logan.error(JSON.stringify(error));
    return Promise.reject(error);
  }
);

// Add a response interceptor
service.interceptors.response.use(
  response =>
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    response
  ,
  (error) => {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    logan.error(JSON.stringify(error));
    errorHandler(error);
    return Promise.reject(error);
  },
);

export default service;
